package lzy.config.security;

import lzy.service.dto.RoleDto;
import lzy.service.dto.User;
import lzy.units.BCryptUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CustomUserDetailsService implements UserDetailsService {


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 这里可以改成从数据库获取账号密码，返回需要登入的信息进行下一步验证
        User user = new User();
        user.setPassword(BCryptUtil.encodeString("123"));
        user.setUserName("lzy");
        RoleDto roleDto = new RoleDto();
        roleDto.setName("ROLE_admin");
        user.setRoleDtos(Arrays.asList(roleDto));

        Set<GrantedAuthority> authorities = new HashSet<>();
        user.getRoleDtos().forEach(role -> {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        });

        return new org.springframework.security.core.userdetails.User(
                user.getUserName(),
                user.getPassword(),
                authorities
        );
    }
}
